/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mohammedalaa.valuecounter.slice;

import com.mohammedalaa.valuecounter.ResourceTable;
import com.mohammedalaa.valuecounterlib.ValueCounterView;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

/**
 * Main Ability Slice
 */
public class MainAbilitySlice extends AbilitySlice {
    private ValueCounterView valueCounterView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        valueCounterView = (ValueCounterView) findComponentById(ResourceTable.Id_valueCounter);
        findComponentById(ResourceTable.Id_getValue)
                .setClickedListener(component ->
                        showDialog(valueCounterView.getValue() + ""));
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void showDialog(String ps) {
        ToastDialog dialog = new ToastDialog(getAbility());
        Component component = LayoutScatter.getInstance(getAbility())
                .parse(ResourceTable.Layout_toast_layout, null, false);
        Text text = (Text) component.findComponentById(ResourceTable.Id_toast_text);
        text.setText(ps);
        dialog.setDuration(500);
        dialog.setComponent(component);
        dialog.setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT);
        dialog.setAlignment(LayoutAlignment.BOTTOM | LayoutAlignment.HORIZONTAL_CENTER);
        dialog.show();
    }
}
